/**
 * Copyright (C) 2017-2018 pinganfang, Inc. All Rights Reserved.
 */
package com.pingan.haofang.searchcloud.register.metadata;

import com.pingan.haofang.framework.common.functional.lang.control.base.Enums;
import com.pingan.haofang.searchcloud.api.matedata.FieldMeta;
import com.pingan.haofang.searchcloud.api.matedata.IndexMeta;
import com.pingan.haofang.searchcloud.api.matedata.constant.MetadataFieldType;
import com.pingan.haofang.searchcloud.index.dto.IndexInfoQueryResult;
import com.pingan.haofang.searchcloud.metadata.dto.MetadataFieldQueryResult;

import java.util.HashMap;
import java.util.Map;

/**
 * @author huhailiang937
 * @date 2017年6月20日下午4:48:04
 * @since 1.0.0
 */
public class IndexMetaTransfer {

    /**
     * @param indexInfo
     * @return
     */
    public static IndexMeta indexInfo2IndexMeta(IndexInfoQueryResult indexInfo) {
        IndexMeta index = new IndexMeta();
        index.setIndexName(indexInfo.getBasicInfo().getIndexName());
        index.setHost(indexInfo.getBasicInfo().getHost());
        index.setEngineType(indexInfo.getBasicInfo().getEngineType());
        index.setShardCount(indexInfo.getBasicInfo().getShardCount());
        index.setReplicationFactor(indexInfo.getBasicInfo().getReplicationFactor());

        Map<String, FieldMeta> filedMetas = new HashMap<String, FieldMeta>(indexInfo.getFields().size() * 2);
        for (MetadataFieldQueryResult metadataField : indexInfo.getFields()) {
            FieldMeta fieldMeta = new FieldMeta();
            String name = metadataField.getFieldName();
            fieldMeta.setName(name);
            MetadataFieldType metadataFieldType = Enums.find(metadataField.getFieldTypeId(), MetadataFieldType.class)
                    .orElse(MetadataFieldType.STRING);
            fieldMeta.setType(metadataFieldType);
            fieldMeta.setPk(metadataField.isUniqueKey());
            fieldMeta.setMultiValued(metadataField.isMultiValued());
            fieldMeta.setRequired(metadataField.isRequired());
            fieldMeta.setIndexed(metadataField.isIndexed());
            fieldMeta.setVersionKey(metadataField.isVersionKey());

            if (metadataField.isUniqueKey()) {
                index.setPk(fieldMeta);
            }
            if (metadataField.isVersionKey()) {
                index.setVersionField(fieldMeta);
            }

            filedMetas.put(name, fieldMeta);
        }
        index.setFiledMetas(filedMetas);

        return index;
    }
}
